using ComponentSystem;
using UnityEngine;

namespace UnityActionSystem.Samples
{
    /// <summary>
    /// 事件系统使用示例
    /// 展示如何在实际游戏中使用事件系统
    /// </summary>
    public class EventSystemExample : MonoBehaviour
    {
        [Header("示例设置")]
        [SerializeField] private bool enableAutoDemo = true;
        [SerializeField] private float demoInterval = 2f;

        private EventBusEntity _eventBus;
        private float _lastDemoTime;

        private void Start()
        {
            _eventBus = ComponentFactory.CreateEntityCSharp<EventBusEntity>();
            _eventBus.Initialization();
            // 订阅各种事件
            SubscribeToEvents();

            Debug.Log("=== 事件系统示例启动 ===");
            Debug.Log("按空格键手动触发示例事件");
        }

        private void Update()
        {
            // 手动触发示例
            if (Input.GetKeyDown(KeyCode.Space))
            {
                TriggerManualExamples();
            }

            // 自动演示
            if (enableAutoDemo && Time.time - _lastDemoTime > demoInterval)
            {
                TriggerAutoDemo();
                _lastDemoTime = Time.time;
            }
        }

        /// <summary>
        /// 订阅各种事件
        /// </summary>
        private void SubscribeToEvents()
        {
            // 订阅消息事件
            _eventBus.Subscribe<TestMessageEvent>(TestEventIds.TestMessage, OnMessageReceived);

            // 订阅玩家事件
            _eventBus.Subscribe<TestPlayerEvent>(TestEventIds.TestPlayer, OnPlayerEventReceived);

            // 订阅游戏状态事件
            _eventBus.Subscribe<TestGameStateEvent>(TestEventIds.TestGameState, OnGameStateReceived);
        }

        /// <summary>
        /// 手动触发示例
        /// </summary>
        private void TriggerManualExamples()
        {
            Debug.Log("\n--- 手动触发示例 ---");

            // 示例1: 立即执行的消息事件
            _eventBus.Publish(TestEventIds.TestMessage,
                new TestMessageEvent("玩家按下了空格键！", "UserInput"),
                EventPriority.Immediate);

            // 示例2: 高优先级的玩家事件
            _eventBus.Publish(TestEventIds.TestPlayer,
                new TestPlayerEvent(12345, transform.position, "Moving"),
                EventPriority.High);

            // 示例3: 普通优先级的游戏状态事件
            _eventBus.Publish(TestEventIds.TestGameState,
                new TestGameStateEvent("GameRunning", 1),
                EventPriority.Normal);
        }

        /// <summary>
        /// 自动演示
        /// </summary>
        private void TriggerAutoDemo()
        {
            Debug.Log("\n--- 自动演示 ---");

            // 随机选择演示类型
            int demoType = Random.Range(0, 4);

            switch (demoType)
            {
                case 0:
                    DemoMessageEvents();
                    break;
                case 1:
                    DemoPlayerEvents();
                    break;
                case 2:
                    DemoGameStateEvents();
                    break;
                case 3:
                    DemoPriorityComparison();
                    break;
            }
        }

        /// <summary>
        /// 演示消息事件
        /// </summary>
        private void DemoMessageEvents()
        {
            string[] messages = { "系统消息", "警告信息", "错误提示", "成功通知" };
            string[] types = { "System", "Warning", "Error", "Success" };

            int index = Random.Range(0, messages.Length);
            _eventBus.Publish(TestEventIds.TestMessage,
                new TestMessageEvent(messages[index], types[index]),
                EventPriority.Immediate);
        }

        /// <summary>
        /// 演示玩家事件
        /// </summary>
        private void DemoPlayerEvents()
        {
            ulong playerId = (ulong)Random.Range(1000, 9999);
            Vector3 randomPos = new Vector3(
                Random.Range(-10f, 10f),
                Random.Range(0f, 5f),
                Random.Range(-10f, 10f)
            );
            string[] states = { "Idle", "Walking", "Running", "Jumping", "Attacking" };

            string state = states[Random.Range(0, states.Length)];
            _eventBus.Publish(TestEventIds.TestPlayer,
                new TestPlayerEvent(playerId, randomPos, state),
                EventPriority.High);
        }

        /// <summary>
        /// 演示游戏状态事件
        /// </summary>
        private void DemoGameStateEvents()
        {
            string[] gameStates = { "Menu", "Playing", "Paused", "GameOver", "Loading" };
            string state = gameStates[Random.Range(0, gameStates.Length)];
            int value = Random.Range(0, 100);

            _eventBus.Publish(TestEventIds.TestGameState,
                new TestGameStateEvent(state, value),
                EventPriority.Normal);
        }

        /// <summary>
        /// 演示优先级比较
        /// </summary>
        private void DemoPriorityComparison()
        {
            Debug.Log("发送不同优先级的事件，观察执行顺序：");

            // 低优先级
            _eventBus.Publish(TestEventIds.TestMessage,
                new TestMessageEvent("低优先级事件", "Low"),
                EventPriority.Low);

            // 普通优先级
            _eventBus.Publish(TestEventIds.TestMessage,
                new TestMessageEvent("普通优先级事件", "Normal"),
                EventPriority.Normal);

            // 高优先级
            _eventBus.Publish(TestEventIds.TestMessage,
                new TestMessageEvent("高优先级事件", "High"),
                EventPriority.High);

            // 立即执行
            _eventBus.Publish(TestEventIds.TestMessage,
                new TestMessageEvent("立即执行事件", "Immediate"),
                EventPriority.Immediate);
        }

        #region 事件处理器

        /// <summary>
        /// 处理消息事件
        /// </summary>
        private void OnMessageReceived(TestMessageEvent eventData)
        {
            Debug.Log($"[消息处理器] 收到消息: {eventData.Message} (类型: {eventData.MessageType})");
        }

        /// <summary>
        /// 处理玩家事件
        /// </summary>
        private void OnPlayerEventReceived(TestPlayerEvent eventData)
        {
            Debug.Log($"[玩家处理器] 玩家 {eventData.PlayerId} 在位置 {eventData.Position} 状态: {eventData.State}");
        }

        /// <summary>
        /// 处理游戏状态事件
        /// </summary>
        private void OnGameStateReceived(TestGameStateEvent eventData)
        {
            Debug.Log($"[游戏状态处理器] 游戏状态: {eventData.GameState}, 值: {eventData.StateValue}");
        }

        #endregion

        private void OnDestroy()
        {
            // 取消订阅（虽然在这个示例中不是必需的，但这是好的实践）
            if (_eventBus != null)
            {
                _eventBus.Unsubscribe<TestMessageEvent>(TestEventIds.TestMessage, OnMessageReceived);
                _eventBus.Unsubscribe<TestPlayerEvent>(TestEventIds.TestPlayer, OnPlayerEventReceived);
                _eventBus.Unsubscribe<TestGameStateEvent>(TestEventIds.TestGameState, OnGameStateReceived);
            }
            _eventBus.ClearAllListeners();
        }

        private void OnGUI()
        {
            // 显示使用说明
            GUI.Box(new Rect(10, 10, 300, 100), "");
            GUI.Label(new Rect(20, 20, 280, 20), "事件系统示例");
            GUI.Label(new Rect(20, 40, 280, 20), "按空格键手动触发示例");
            GUI.Label(new Rect(20, 60, 280, 20), "自动演示已启用");
            GUI.Label(new Rect(20, 80, 280, 20), "查看Console了解详细信息");
        }
    }
}
